from .forms import CommentForm
from blog.models import Post
from django.contrib import messages
from django.views.decorators.http import require_POST
from django.shortcuts import render, get_object_or_404, redirect, render
# Create your views here.


@require_POST
def comment(request, post_pk):
    # 先获取文章Id
    post = get_object_or_404(Post, pk=post_pk)
    # 利用django将用户提交的数据封装在request.POST中，这是一个类字典对象
    form = CommentForm(request.POST)
    # 检查格式
    if form.is_valid():
        comment = form.save(commit=False)  # False是仅仅利用表单数据生成Comment模型类的实例，但还不保存评论数据到数据库
        comment.post = post     # 关联文章和评论
        comment.save()
        messages.add_message(request, messages.SUCCESS, '评论发表成功！', extra_tags='success')
        return redirect(post)

    context = {
        'post': post,
        'form': form,
    }
    messages.add_message(request, messages.ERROR, '评论发表失败！请修改表单中的错误后重新提交。', extra_tags='danger')
    return render(request, 'comments/preview.html', context=context)
